package com.mingzhi.lotterysystem.service.impl;

import com.mingzhi.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.mingzhi.lotterysystem.common.exception.ServiceException;
import com.mingzhi.lotterysystem.common.utils.*;
import com.mingzhi.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private static final String VERIFICATION_CODE_TEMPLATE_CODE = "SMS_478300083";
    //对于Redis里面的手机号要标准化：
    //是为了区分不同的业务 定义前缀
    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    //设置过期时间
    private static final Long VERIFICATION_CODE_TIMEOUT = 60l;

    @Autowired
    private SMSUtil smsUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String phoneNumber) {
        //1.校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //2.生成随机验证码
        String code = CaptchaUtil.getCaptchaCode(4);
        //3.发送验证码
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        smsUtil.sendMessage(VERIFICATION_CODE_TEMPLATE_CODE,
                phoneNumber,
                JacksonUtil.writeValueAsString(map));
        //4.将验证码存储在 Redis 中
        Boolean set = redisUtil.set(VERIFICATION_CODE_PREFIX + phoneNumber, code, VERIFICATION_CODE_TIMEOUT);

    }

    @Override
    public String getVerificationCode(String phoneNumer) {
        //1.校验手机号
        if (!RegexUtil.checkMobile(phoneNumer)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //2.从 Redis 里面获取验证码
        return redisUtil.get(VERIFICATION_CODE_PREFIX + phoneNumer);
    }
}
